import { addNewContent, findDetail, updateContent } from '@/api/draft';
import { ResultCodeEnum, TEMP_ID_ENUM } from '@/enums';
import { useUserStore } from '@/store';
import { useToast } from 'wot-design-uni';
import type { UploadFile } from 'wot-design-uni/components/wd-upload/types';
import { formatDate, getStartOrEndDate } from '@/utils/date';
import { isNotEmpty } from '@/utils/validate';
import type { CheckboxInstance } from 'wot-design-uni/components/wd-checkbox/types';
import { subscribeMsg } from '@/utils/common';
export const useDraftEdit = () => {
  const id = ref(0);
  const isEditType = ref('');
  onLoad((options: any) => {
    if (options.id) {
      uni.setNavigationBarTitle({ title: '编辑' });
      id.value = options.id;
      getDetail(options.id);
    } else {
      uni.setNavigationBarTitle({ title: '新增' });
    }
    if (options.type) {
      isEditType.value = options.type;
      if (isEditType.value === 'copy') {
        uni.setNavigationBarTitle({ title: '复制' });
      }
    }
  });

  const startDate = Date.now();
  const { end } = getStartOrEndDate('year');
  const endDate = end.valueOf();

  const getDetail = async (id: number) => {
    const res = await findDetail(id);
    if (res.code === ResultCodeEnum.SUCCESS) {
      model.value.taskName = res.data.taskName;
      model.value.content = res.data.content;
      model.value.images = res.data.images;
      model.value.tag = res.data.tag;
      model.value.date = res.data.date;
      model.value.time = res.data.time;
      model.value.isTemplate = res.data.isTemplate;
      fileList.value = res.data.images
        ? res.data.images.split(',').map((url) => ({ url }))
        : [];
    }
  };

  const action = `${import.meta.env.VITE_APP_UPLOAD_URL}?id=${useUserStore().userInfo.id}`;

  type Model = {
    taskName: string;
    content: string;
    images: string;
    tag: string;
    date: string;
    time: string;
    isTemplate: boolean;
    // count: number;
    // interval: number;
  };

  const getRule = (message: string) => [
    {
      required: false,
      validator: isNotEmpty,
      message
    }
  ];
  const fileList = ref<UploadFile[]>([]);
  const formRef = ref();
  const model = ref<Model>({
    taskName: '',
    content: '',
    images: '',
    tag: '',
    date: '',
    time: '',
    isTemplate: false
    // count: 1,
    // interval: 0
  });

  const checkBox = ref<CheckboxInstance>();

  function handleCheck() {
    checkBox.value && checkBox.value.toggle();
  }

  const handleChange = ({ fileList }: any) => {
    console.log('打印***fileList', fileList);
    if (fileList.length) {
      const list = fileList.map((item: any) => {
        return JSON.parse(item.response).data.url;
      });
      model.value.images = list.join(',');
    } else {
      model.value.images = '';
    }
  };
  const { success: showSuccess } = useToast();

  const noop = () => { };

  const handleSubmit = async () => {
    console.log('handleSubmit', model.value);
    const { valid } = await formRef.value.validate();
    console.log('打印***valid', valid);
    if (!valid) return;
    let res = null;
    const date = formatDate(model.value.date);
    if (id.value && isEditType.value === 'edit') {
      res = await updateContent({ id: id.value, ...model.value, date });
    } else {
      res = await addNewContent({ ...model.value, date });
    }
    if (res.code === ResultCodeEnum.SUCCESS) {
      await subscribeMsg(TEMP_ID_ENUM.SHORT_TIMING);
      showSuccess({
        msg: '保存成功'
      });
      setTimeout(() => {
        uni.redirectTo({ url: '/pages/moments/drafts/index' });
      }, 2000);
    }
  };

  return {
    startDate,
    endDate,
    fileList,
    formRef,
    model,
    action,
    getRule,
    handleCheck,
    handleChange,
    noop,
    handleSubmit
  };
};
